using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using twistmachinev2.CommonUse;
using twistmachinev2.Entity;
using twistmachinev2.Repository;

namespace twistmachinev2.Business
{
    public partial class FrmLogin : DevExpress.XtraEditors.XtraForm
    {
        private List<PUser> users; // 模拟用户数据
        private SqliteRepository repository;
        public FrmLogin()
        {
            InitializeComponent();
            this.labelControl3.Text = BaseData.GetSystemName();
            keyBoard.Visible = false;
            repository = new SqliteRepository();
            InitializeForm();
            InitializeUsers();
        }

        private void InitializeForm()
        {
            // 设置窗体属性
            this.Text = "系统登录";
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            // this.Size = new Size(450, 350);

            // 设置背景色
            this.BackColor = Color.FromArgb(240, 244, 247);

            // 设置窗体图标和样式
            this.IconOptions.ShowIcon = false;
            this.LookAndFeel.UseDefaultLookAndFeel = false;
            this.LookAndFeel.SkinName = "Office 2019 Colorful";

            // 设置默认按钮
            this.AcceptButton = btnLogin;
            this.CancelButton = btnCancel;

            // 焦点设置
            txtUsername.Focus();
        }

        private void InitializeUsers()
        {
            // 初始化模拟用户数据
            users = repository.GetList<PUser>().ToList();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (ValidateInput())
            {
                var user = AuthenticateUser(txtUsername.Text.Trim(), txtPassword.Text.Trim());
                if (user != null)
                {
                    if (user.UserStatus == "启用")
                    {
                        // 保存用户信息到BaseData
                        SaveUserToBaseData(user);

                        // 显示登录成功信息
                        //XtraMessageBox.Show($"欢迎您，{user.UserName}！", "登录成功",
                        //    MessageBoxButtons.OK, MessageBoxIcon.Information);

                        // 设置对话框结果并关闭窗体
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        XtraMessageBox.Show("用户已被停用，请联系管理员！", "登录失败",
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtPassword.Focus();
                        txtPassword.SelectAll();
                    }
                }
                else
                {
                    XtraMessageBox.Show("用户名或密码错误！", "登录失败",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtPassword.Focus();
                    txtPassword.SelectAll();
                }
            }
        }

        private bool ValidateInput()
        {
            if (string.IsNullOrWhiteSpace(txtUsername.Text))
            {
                XtraMessageBox.Show("请输入用户名！", "验证失败",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtUsername.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtPassword.Text))
            {
                XtraMessageBox.Show("请输入密码！", "验证失败",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPassword.Focus();
                return false;
            }

            return true;
        }

        private PUser AuthenticateUser(string username, string password)
        {
            return users.FirstOrDefault(u => u.UserId.Equals(username, StringComparison.OrdinalIgnoreCase)
                                           && u.Password == password);
        }

        private void SaveUserToBaseData(PUser user)
        {
            // 将用户信息保存到BaseData静态类中
            BaseData.CurrentUser = user;
            //BaseData.WorkStation = user.UserId;
            //BaseData.SystemName = user.UserName;

            // 设置登录用户属性
            LoggedInUser = user;

            // 记录登录日志
            // 用户登录系统
        }

        private string GetPermissionName(long permissionValue)
        {
            switch (permissionValue)
            {
                case 30:
                    return "操作员";
                case 60:
                    return "管理员";
                case 90:
                    return "超级管理员";
                default:
                    return "未知权限";
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 回车键登录
            if (e.KeyChar == (char)Keys.Enter)
            {
                btnLogin_Click(sender, e);
                e.Handled = true;
            }
        }

        private void txtUsername_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 回车键移动到密码框
            if (e.KeyChar == (char)Keys.Enter)
            {
                txtPassword.Focus();
                e.Handled = true;
            }
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {
            // 窗体加载时的初始化
            txtUsername.Focus();
        }

        // 公共属性，用于获取登录的用户信息
        public PUser LoggedInUser { get; private set; }

        private void keyBoard_RetractClike(object sender, EventArgs e)
        {
            keyBoard.Visible = false;
        }

        private void txtUsername_MouseEnter(object sender, EventArgs e)
        {
            //keyBoard.Visible = true;
        }

        private void txtUsername_MouseDown(object sender, MouseEventArgs e)
        {
            keyBoard.Visible = true;
        }
    }
}